class Document < ActiveRecord::Base
  depends_on :content, :attrs => [:name], 
             :as => :presentable, :dependent => :destroy
  has_many :document_versions, :order => "version_number desc", :dependent => :destroy
  belongs_to :document_category

  attr_accessor :version

  after_save :maybe_save_new_version

  def current_version
    DocumentVersion.current_version_for_document_id(self.id)
  end

  private
  def maybe_save_new_version
    return unless self.version
    next_version = 1 + (DocumentVersion.current_version_id_for_document_id(self.id) || 0 )
    DocumentVersion.create  :document_id => self.id,
                            :version_number => next_version,
                            :version => self.version
  end

end
